import streamlit as st
import re
from util.database import init_db, create_user, verify_user, username_exists, email_exists, get_user_count

# 初始化数据库
init_db()


def show_login():
    """显示登录页面"""
    st.markdown('<h2 class="main-header">登录</h2>', unsafe_allow_html=True)

    with st.form("login_form"):
        username = st.text_input("用户名", placeholder="请输入您的用户名")
        password = st.text_input("密码", type="password", placeholder="请输入您的密码")

        col1, col2 = st.columns([1, 2])
        with col1:
            login_submitted = st.form_submit_button("登录")
        with col2:
            st.write("没有账号?")
            if st.form_submit_button("创建新账号"):
                st.session_state.auth_page = "register"
                st.rerun()

        if login_submitted:
            if not username or not password:
                st.error("请填写用户名和密码")
            elif verify_user(username, password):
                st.session_state.logged_in = True
                st.session_state.username = username
                st.success("登录成功!")
                st.rerun()
            else:
                st.error("用户名或密码错误")


def show_register():
    """显示注册页面"""
    st.markdown('<h2 class="main-header">创建账号</h2>', unsafe_allow_html=True)

    with st.form("register_form"):
        username = st.text_input("用户名", placeholder="请输入用户名 (3-20个字符)")
        email = st.text_input("邮箱", placeholder="请输入邮箱地址")
        password = st.text_input("密码", type="password", placeholder="请输入密码 (至少6个字符)")
        confirm_password = st.text_input("确认密码", type="password", placeholder="请再次输入密码")

        col1, col2 = st.columns([1, 2])
        with col1:
            register_submitted = st.form_submit_button("创建账号")
        with col2:
            st.write("已有账号?")
            if st.form_submit_button("返回登录"):
                st.session_state.auth_page = "login"
                st.rerun()

        if register_submitted:
            # 验证输入
            if not username or not email or not password or not confirm_password:
                st.error("请填写所有字段")
            elif len(username) < 3 or len(username) > 20:
                st.error("用户名长度必须在3-20个字符之间")
            elif not re.match(r"[^@]+@[^@]+\.[^@]+", email):
                st.error("请输入有效的邮箱地址")
            elif len(password) < 6:
                st.error("密码长度至少为6个字符")
            elif password != confirm_password:
                st.error("两次输入的密码不一致")
            elif username_exists(username):
                st.error("用户名已存在")
            elif email_exists(email):
                st.error("邮箱已被注册")
            else:
                if create_user(username, password, email):
                    st.success("账号创建成功! 请返回登录页面")
                    # 自动切换到登录页面
                    st.session_state.auth_page = "login"
                    st.rerun()
                else:
                    st.error("创建账号失败，请稍后重试")


def show():
    """显示认证页面"""
    # 初始化session状态
    if "auth_page" not in st.session_state:
        st.session_state.auth_page = "login"
    if "logged_in" not in st.session_state:
        st.session_state.logged_in = False

    # 如果已登录，显示欢迎信息
    if st.session_state.logged_in:
        st.sidebar.success(f"欢迎, {st.session_state.username}!")
        if st.sidebar.button("退出登录"):
            st.session_state.logged_in = False
            st.session_state.username = None
            st.rerun()
        return True

    # 显示登录或注册页面
    if st.session_state.auth_page == "login":
        show_login()
    else:
        show_register()

    # 显示用户统计信息
    user_count = get_user_count()
    st.sidebar.info(f"已注册用户: {user_count}")

    return False


# 确保模块可以独立运行
if __name__ == "__main__":
    show()